package cli;

import database.DatabaseHelper;
import entity.Score;
import entity.Section;
import statistic.StudentScoreList;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class SectionScore implements CommandLineInterface.Handler {

    DatabaseHelper db;

    private Section inputSection(Scanner in, PrintWriter out) throws SQLException {
        out.println("请输入教学班号：");
        String secId = in.next();
        return Section.find(db, secId);
    }

    private StudentScoreList.Order inputOrder(Scanner in, PrintWriter out) {
        out.println("学生按学号排序，还是按成绩排序？");
        return in.next().contains("学号") ? StudentScoreList.Order.ID : StudentScoreList.Order.SCORE;
    }

    private void output(PrintWriter out, StudentScoreList list) {
        if (list == null)
            return;
        String[] header = {"学号", "姓名", "平时成绩", "期中成绩", "实验成绩", "期末成绩", "总成绩", "取得时间"};
        String[][] table = new String[list.students.size()][header.length];
        for (int i = 0; i < list.students.size(); ++i) {
            table[i][0] = list.students.get(i).getId();
            table[i][1] = list.students.get(i).getName();
            table[i][2] = String.format("%.0f", list.scores.get(i).getUsual());
            table[i][3] = String.format("%.0f", list.scores.get(i).getMidterm());
            table[i][4] = String.format("%.0f", list.scores.get(i).getExperiment());
            table[i][5] = String.format("%.0f", list.scores.get(i).getTerminal());
            table[i][6] = String.format("%.0f", list.scores.get(i).getTotal());
            table[i][7] = list.scores.get(i).getTimeStamp().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
        }
        out.println(new TableLayout(header, table));
    }

    @Override
    public void handle(Scanner in, PrintWriter out) {
        try {
            db = new DatabaseHelper();
            Section sec = inputSection(in, out);
            if (sec == null) {
                out.println("教学班不存在！");
                return;
            }
            StudentScoreList.Order ord = inputOrder(in, out);
            StudentScoreList list = new StudentScoreList(sec, ord);
            output(out, list);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            db.close();
        }
    }
}
